//
//  CallOutViewController.m
//  HollyPhoneSdk
//
//  Created by hollycrm on 2023/3/12.
//

#import "CallOutViewController.h"
#import "Wrapper.h"
#import "AudioManager.h"
#import "HollyPhoneManager.h"
#import "HollyPhoneProtocol.h"
#import "Utils.h"
#import "HollyPhoneSdk.h"

#define serviceLogoSize 80

@interface CallOutViewController ()<HollyPhoneProtocol>{
 
}
@property(nonatomic,strong) UILabel *initversionLabel;
@property (unsafe_unretained, nonatomic) IBOutlet UILabel *versionLabel;
@property (unsafe_unretained, nonatomic) IBOutlet NSLayoutConstraint *hangUpBottomSpace;
@property (unsafe_unretained, nonatomic) IBOutlet NSLayoutConstraint *logoHeight;
@property (unsafe_unretained, nonatomic) IBOutlet NSLayoutConstraint *logoBottomSpace;
@property (unsafe_unretained, nonatomic) IBOutlet NSLayoutConstraint *logoWidth;
@property (unsafe_unretained, nonatomic) IBOutlet NSLayoutConstraint *numberViewHeight;

@property (unsafe_unretained, nonatomic) IBOutlet NSLayoutConstraint *swithBtTrailing;

@property (unsafe_unretained, nonatomic) IBOutlet UIImageView *logoImgView;
@property (unsafe_unretained, nonatomic) IBOutlet UIButton *versionBt;

@property (weak, nonatomic) IBOutlet UIView *operationView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *speakerHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *speakerWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *keybWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *keybHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *muteHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *muteWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *switchWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *switchHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *hangupWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *hangupHeight;

@property (weak, nonatomic) IBOutlet UITextField *dialTf;
@property (weak, nonatomic) IBOutlet UIView *numberView;
@property (weak, nonatomic) IBOutlet UIButton *keyboardBt;
@property (weak, nonatomic) IBOutlet UIButton *hangupBt;
@property (weak, nonatomic) IBOutlet UIButton *micBt;
@property (weak, nonatomic) IBOutlet UIButton *speakerBt;
@property (weak, nonatomic) IBOutlet UIButton *switchBt;
@property (unsafe_unretained, nonatomic) IBOutlet UIButton *exitBt;
@property (strong, nonatomic) NSBundle * bundle;
@property (unsafe_unretained, nonatomic) IBOutlet UILabel *label1;
@property (unsafe_unretained, nonatomic) IBOutlet UILabel *label2;
@property (strong,nonatomic) UIColor *numBgColor;
@property (strong,nonatomic) UIColor *normalBgColor;
@property (strong,nonatomic) UIColor *selectBgColor;
@property (strong,nonatomic) UIView *loadingview;
//let titles:[[String]] = [["1","2","3"],["4","5","6"],["7","8","9"],["*","0","#"]]

@end

@implementation CallOutViewController


- (IBAction)exitClick:(id)sender {

  [self dismissViewControllerAnimated:true completion:^{
   [HollyPhoneManager shareManager].phoneStatus.background = true;
  }];
}

- (IBAction)hangUpClick:(id)sender {
 printf("hangupclick");
 //if ([HollyPhoneManager shareManager].phoneStatus.callStatus != 0){
 [[CPPWrapper new] hangupCallWrapper];
 //}
 if([HollyPhoneManager shareManager].phoneStatus.serviceCallMode){
  [[HollyPhoneManager shareManager] unregister];
 }
 [[HollyPhoneManager shareManager].phoneStatus reset];
 [self dismissViewControllerAnimated:true completion:nil];
}

- (IBAction)micClick:(id)sender {
 printf("micClick");
 
 if ([AudioManager shared]._isMicOn){
  [[AudioManager shared] closeMic];
 }
 else{
  [[AudioManager shared] openMic];
 }
 [self refreshMic];
}

-(void)refreshSpeaker{
 if([AudioManager shared]._isSpeakerOn){
  NSString *file1 = [_bundle pathForResource:@"speak_select" ofType:@"png"];
  UIImage *image1 = [UIImage imageWithContentsOfFile:file1];
  [_speakerBt setImage:image1 forState:UIControlStateNormal];
  _speakerBt.layer.backgroundColor = _selectBgColor.CGColor;
  
 }
 else{
  NSString *file2 = [_bundle pathForResource:@"speak_normal" ofType:@"png"];
  UIImage *image2 = [UIImage imageWithContentsOfFile:file2];
  [_speakerBt setImage:image2 forState:UIControlStateNormal];
  _speakerBt.layer.backgroundColor = _normalBgColor.CGColor;
 }
}
-(void)refreshMic{
 if ([AudioManager shared]._isMicOn){
  NSString *file1 = [_bundle pathForResource:@"mute_normal" ofType:@"png"];
  UIImage *image1 = [UIImage imageWithContentsOfFile:file1];
  [_micBt setImage:image1 forState:UIControlStateNormal];
  _micBt.layer.backgroundColor = _normalBgColor.CGColor;
 }
 else{
  NSString *file2 = [_bundle pathForResource:@"mute_select" ofType:@"png"];
  UIImage *image2 = [UIImage imageWithContentsOfFile:file2];
  [_micBt setImage:image2 forState:UIControlStateNormal];
  _micBt.layer.backgroundColor = _selectBgColor.CGColor;
 }
}

- (IBAction)speakerClick:(id)sender {
 printf("speakerClick");
 if([AudioManager shared]._isSpeakerOn){
  [[AudioManager shared] setSpeakerOff];
 }
 else{
  [[AudioManager shared] setSpeakerOn];
 }
 [self refreshSpeaker];
}

- (void)viewDidLoad {
 NSLog(@"-------------viewdidload");
 [super viewDidLoad];
 [HollyPhoneManager shareManager].phoneStatus.background = false;
 [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CallPageChange object:@"callPageOpen"]];
 
 self.view.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:1];
 
 _numBgColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.1];
 _normalBgColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.1];
 _selectBgColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1];
 [_versionBt setTitle:@"" forState:UIControlStateNormal];
 
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(regStateNotification:) name:hollyPhoneRegStateChange object:nil];
 _label2.text = @"";
 if(![HollyPhoneManager shareManager].phoneStatus.serviceCallMode){
  _label1.text = [HollyPhoneManager shareManager].phoneStatus.phoneNum;
 }
 else{
  _label1.text = @"";
 }
 
 
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callTimeChange) name:hollyPhoneCallTimeChange object:nil];
 
 if([HollyPhoneManager shareManager].phoneStatus.serviceCallMode && [HollyPhoneManager shareManager].logoImg != nil){
  self.logoHeight.constant = serviceLogoSize;
  self.logoWidth.constant = serviceLogoSize;
  self.logoBottomSpace.constant = 10;
  self.numberViewHeight.constant = 380;
  self.hangUpBottomSpace.constant = 40;
  self.logoImgView.image = [HollyPhoneManager shareManager].logoImg;
 }
 
 [self initDialView];
 [self refreshOperationView];
 [self refreshSpeaker];
 [self refreshMic];
 
 if (!_isRestore){
  if ([HollyPhoneManager shareManager].phoneStatus.serviceCallMode){
   if(_needInitView){
    [self showLoadingView];
   }
  }
  else{
   
   [[CPPWrapper new] outgoingCallWrapper:[HollyPhoneManager shareManager].phoneStatus.callId :[HollyPhoneManager shareManager].phoneStatus.params];
   
   [self initAudioSession];
   
  }
 }
 
}

-(void)initAudioSession{
 [[AudioManager shared] setSpeakerOn];
 [self refreshSpeaker];
 AVAudioSession *audioSession = [AVAudioSession sharedInstance];
 NSError *error;
 [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
 if (error) {
     NSLog(@"Failed to set audio session category: %@", error.localizedDescription);
 }
 [audioSession setActive:YES error:&error];
 if (error) {
     NSLog(@"Failed to activate audio session: %@", error.localizedDescription);
 }
 
}

- (void)viewDidAppear:(BOOL)animated{
 NSLog(@"-------------viewdidappear");
 [super viewDidAppear:animated];
 if(_loadingview != nil){
  _loadingview.frame = CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height);
 }
}

-(void)showLoadingView{

     _loadingview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height)];
     _loadingview.backgroundColor = [UIColor blackColor];
      
     [self.view addSubview:_loadingview];

     UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];

     backButton.tintColor = [UIColor whiteColor];
     backButton.frame = CGRectMake(30, 20, 60, 40); // 调整位置和大小
     [backButton.titleLabel setFont:[UIFont systemFontOfSize:22.0]];
     [backButton setTitle:@"X" forState:UIControlStateNormal];
  
     [backButton addTarget:self action:@selector(loadingBackClick) forControlEvents:UIControlEventTouchUpInside];
     [_loadingview addSubview:backButton];
     
 _initversionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, UIScreen.mainScreen.bounds.size.width, 400.0)];
 _initversionLabel.textAlignment = NSTextAlignmentCenter;
 _initversionLabel.textColor = UIColor.whiteColor;
 _initversionLabel.font = [UIFont systemFontOfSize:17.0];
 _initversionLabel.hidden = true;
 [_initversionLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(initVersionClick:)]];
 _initversionLabel.text = [NSString stringWithFormat:@"Version:%@",SDK_VERSION];
 [_loadingview addSubview:_initversionLabel];
 
 

     UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
     activityIndicator.center = CGPointMake(UIScreen.mainScreen.bounds.size.width/2 -10, UIScreen.mainScreen.bounds.size.height/2 -10);
     [activityIndicator startAnimating]; // 开始旋转动画
     [_loadingview addSubview:activityIndicator];
 [self.view addSubview:_loadingview];
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initStateChange:) name:InitStateChange object:nil];
}

-(void)removeLoadingView{
 [_loadingview removeFromSuperview];
 _loadingview = nil;
}
-(void)loadingBackClick{
 [self dismissViewControllerAnimated:true completion:^{
  [[HollyPhoneManager shareManager] unregister];
 }];
}

-(void)initStateChange:(NSNotification *)notify{
 if([notify.object isEqualToString:InitSuccess]){
  [self removeLoadingView];
  
   [[CPPWrapper new] outgoingServiceCallWrapper:[HollyPhoneManager shareManager].phoneStatus.callId withIp:[HollyPhoneManager shareManager].phoneStatus.ip andPort:[HollyPhoneManager shareManager].phoneStatus.port andPhoneNum:[HollyPhoneManager shareManager].phoneStatus.fromNum andParams:[HollyPhoneManager shareManager].phoneStatus.params];
  [self initAudioSession];
 }
 else{
  [[HollyPhoneManager shareManager] unregister];
  [self dismissViewControllerAnimated:true completion:nil];
 }
}

-(void)dealloc{
 NSLog(@"-------------viewdealloc");
 [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CallPageChange object:@"callPageClose"]];
 [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)callTimeChange{
 int second = [HollyPhoneManager shareManager].phoneStatus.callSeconds;
 self.label2.text = [Utils getCallTimeStr:second];
}


- (IBAction)switchBtClick:(id)sender {
 [HollyPhoneManager shareManager].phoneStatus.opViewType = 0;
 [self refreshOperationView];
}
- (IBAction)keyBoardBtClick:(id)sender {
 [HollyPhoneManager shareManager].phoneStatus.opViewType = 1;
 [self refreshOperationView];
}

-(void)initOperationView:(CGFloat)size{
 self.muteWidth.constant = size;
 self.muteHeight.constant = size;
 self.keybWidth.constant = size;
 self.keybHeight.constant = size;
 self.speakerWidth.constant = size;
 self.speakerHeight.constant = size;
 self.hangupWidth.constant = size;
 self.hangupHeight.constant = size;
 self.switchWidth.constant = size * 0.4;
 self.switchHeight.constant = size * 0.4;
 
 self.micBt.layer.backgroundColor = _normalBgColor.CGColor;
 self.keyboardBt.layer.backgroundColor = _normalBgColor.CGColor;
 self.speakerBt.layer.backgroundColor = _normalBgColor.CGColor;
 
 UIEdgeInsets imgInsets = UIEdgeInsetsMake(15, 15, 15, 15);
 UIEdgeInsets bigEdge = UIEdgeInsetsMake(20, 20, 20, 20);
 self.micBt.layer.masksToBounds = YES;
 self.micBt.layer.cornerRadius = size/2;
 [self.micBt setImageEdgeInsets:bigEdge];
 
 self.keyboardBt.layer.masksToBounds = YES;
 self.keyboardBt.layer.cornerRadius = size/2;
 [self.keyboardBt setImageEdgeInsets:imgInsets];
 
 self.speakerBt.layer.masksToBounds = YES;
 self.speakerBt.layer.cornerRadius = size/2;
 [self.speakerBt setImageEdgeInsets:bigEdge];
 
 self.hangupBt.layer.masksToBounds = YES;
 self.hangupBt.layer.cornerRadius = size/2;
 [self.hangupBt setImageEdgeInsets:imgInsets];
 
}

-(void)refreshOperationView{
 if([HollyPhoneManager shareManager].phoneStatus.opViewType == 0){
  self.numberView.hidden = true;
  self.operationView.hidden = false;
  self.switchBt.hidden = true;
 }
 else{
  self.numberView.hidden = false;
  self.operationView.hidden = true;
  self.switchBt.hidden = false;
 }
}

-(void)initDialView{
 self.label1.font = [UIFont systemFontOfSize:32.0];
 self.label2.font = [UIFont systemFontOfSize:19.0];
 NSArray *titles = @[@[@"1",@"2",@"3"],@[@"4",@"5",@"6"],@[@"7",@"8",@"9"],@[@"*",@"0",@"#"]];
 CGFloat xmargin = 20;
 CGFloat gridHeight = self.numberViewHeight.constant/4;
 CGFloat gridWidth = (UIScreen.mainScreen.bounds.size.width - xmargin * 2)/3;
 CGFloat btSize = gridWidth > gridHeight ? gridHeight - 20 : gridWidth - 20;
 
 [self initOperationView:btSize];
 
 CGFloat xpadding = (gridWidth - btSize)/2;
 CGFloat ypadding = (gridHeight - btSize)/2;
 self.swithBtTrailing.constant = xpadding + xmargin;
 CGFloat origin_y = 0;
 for(int i = 0 ; i < 4; i ++){
  origin_y =  ypadding*i*2 + ypadding + btSize * i;
  CGFloat origin_x = xmargin;
  for(int j = 0 ; j < 3; j++){
   origin_x =xmargin + xpadding*j*2 + xpadding + btSize * j;
   UIButton *bt = [[UIButton alloc] initWithFrame:CGRectMake(origin_x, origin_y, btSize, btSize)];
   bt.layer.masksToBounds = YES;
   bt.layer.cornerRadius = btSize/2;
   bt.titleLabel.font = [UIFont systemFontOfSize:34.0];
   bt.backgroundColor = _numBgColor;
   //            [bt setBackgroundImage:[Utils imageWithColor:[UIColor darkGrayColor]] forState:UIControlStateHighlighted];
   [bt setTitle:titles[i][j] forState:UIControlStateNormal];
   [bt addTarget:self action:@selector(numberBtClick:) forControlEvents:UIControlEventTouchUpInside];
   [_numberView addSubview:bt];
  }
 }
}

-(void)numberBtClick:(id)sender{
 if([sender isKindOfClass:[UIButton class]]){
  UIButton *dialBt = sender;
  [[CPPWrapper new] dialNum:dialBt.titleLabel.text];
  if([HollyPhoneManager shareManager].phoneStatus.serviceCallMode){
   
   _label1.text = [NSString stringWithFormat:@"%@%@",_label1.text,dialBt.titleLabel.text];
  }
 }
}

-(void)regStateNotification:(NSNotification *)noti{
 
}

-(instancetype)init{
 _bundle = [Utils getSdkBundle];
 
 self = [super initWithNibName:@"CallOutViewController" bundle:_bundle];
 
 return self;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (void)callStatusChanged:(int)status {
 
}


- (IBAction)showVersionClick:(id)sender {
 self.versionLabel.text = [NSString stringWithFormat:@"%@",SDK_VERSION];
}

-(void)initVersionClick:(id)sender {
 _initversionLabel.hidden = false;
}
@end
